use anyhow::Result;
use tokio::net::TcpListener;
use tokio_web_demo::{
    app_state,
    config::{self, AppConfig},
    routers::get_router,
};
use tracing::level_filters::LevelFilter;
use tracing_subscriber::{fmt::Layer, layer::SubscriberExt, util::SubscriberInitExt, Layer as _};

#[tokio::main]
async fn main() -> Result<()> {
    let layer = Layer::new().with_filter(LevelFilter::INFO);
    tracing_subscriber::registry().with(layer).init();
    let config = AppConfig::load()?;
    let addr = format!("{}:{}", "0.0.0.0", config.server.port);
    let listener = TcpListener::bind(addr).await?;
    tracing::info!("listening on {}", listener.local_addr()?);
    let state = app_state::AppState::try_new(config).await?;
    let app = get_router(state).await?;
    axum::serve(listener, app.into_make_service()).await?;
    Ok(())
}
